﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FlowersStore
{
	public partial class AdminCategories : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				FlowerStoreDataContext db = new FlowerStoreDataContext();
				if (Request.QueryString["dept"] == null)
				{

					long dept_id = db.Departments.First().Department_id;
					Response.Redirect(Request.RawUrl + "?dept=" + dept_id.ToString());
				}
				else
				{
					ddlDapartments.DataBind();
					if (db.Departments.SingleOrDefault(d => d.Department_id == int.Parse(Request.QueryString["dept"].ToString())) == null)
						Response.Redirect("AdminCategories.aspx");
					else
						ddlDapartments.SelectedValue = Request.QueryString["dept"].ToString();
				}
			}
			
		}

		protected void ddlDapartments_SelectedIndexChanged(object sender, EventArgs e)
		{		
			Response.Redirect("AdminCategories.aspx?dept=" + ddlDapartments.SelectedValue);
		}

		protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
		{
			InsertCategory(e.Item);
		}

		void InsertCategory(ListViewItem item)
		{
			if (IsValid)
			{
				using (FlowerStoreDataContext db = new FlowerStoreDataContext())
				{
					Category cat = new Category();
					cat.Category_name = ((TextBox)item.FindControl("Category_nameTextBox")).Text;
					cat.Category_description = ((TextBox)item.FindControl("Category_descriptionTextBox")).Text;
					cat.Department_id = int.Parse(((DropDownList)item.FindControl("departments")).SelectedValue);
					db.Categories.InsertOnSubmit(cat);
					db.SubmitChanges();
					ListView1.DataBind();
				}
			}
		}

		void UpdateCategory(string categoryId,ListViewItem item)
		{
			if (IsValid)
			{
				using (FlowerStoreDataContext db = new FlowerStoreDataContext())
				{
					Category cat = (from c in db.Categories
									where c.Category_id == int.Parse(categoryId)
									select c).Single();
					cat.Category_name = ((TextBox)item.FindControl("Category_nameTextBox")).Text;
					cat.Category_description = ((TextBox)item.FindControl("Category_descriptionTextBox")).Text;
					cat.Department_id = int.Parse(((DropDownList)item.FindControl("departments")).SelectedValue);
					db.SubmitChanges();
					Response.Redirect(Request.RawUrl);
				}
			}
		}

		protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
		{
			UpdateCategory(e.Keys["Category_id"].ToString(), ListView1.Items[e.ItemIndex]);
		}
	}
}